package com.ly.heart.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ly.common.PageParam;
import com.ly.common.core.domain.AjaxResult;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.erp.ConstUtil;
import com.ly.heart.domain.KingInventoryEntity;
import com.ly.heart.domain.KingProfitLossDetailEntity;
import com.ly.heart.domain.KingProfitLossEntity;
import com.ly.heart.domain.dto.KingProfitLossDto;
import com.ly.heart.domain.dto.KingRealInventoryDto;
import com.ly.heart.domain.dto.KingRealInventoryQueryDto;
import com.ly.heart.mapper.KingRealInventoryMapper;
import com.ly.heart.service.IKingInventoryService;
import com.ly.heart.service.IKingProfitLossService;
import com.ly.heart.service.IKingRealInventoryService;
import com.ly.heart.util.CurrentUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.ly.heart.domain.KingRealInventoryEntity;

import javax.annotation.Resource;

/**
 * 金蝶-即时库存，出入库实时更新Service业务层处理
 *
 * @author wutao
 * @date 2024-07-24
 */
@Service
@Slf4j
public class KingRealInventoryServiceImpl extends ServiceImpl<KingRealInventoryMapper, KingRealInventoryEntity> implements IKingRealInventoryService {

    @Resource
    private KingRealInventoryMapper kingRealInventoryMapper;
    @Resource
    private IKingProfitLossService iKingProfitLossService;
    @Resource
    private IKingInventoryService iKingInventoryService;


    /**
     * 查询金蝶-即时库存，出入库实时更新
     *
     * @param id 金蝶-即时库存，出入库实时更新ID
     * @return 金蝶-即时库存，出入库实时更新
     */
    @Override
    public KingRealInventoryEntity selectKingRealInventoryEntityById ( String id ) {
        return kingRealInventoryMapper.selectKingRealInventoryEntityById ( id );
    }

    /**
     * 查询金蝶-即时库存，出入库实时更新列表
     * 根据某仓库拉取所有物料的事实库存信息
     *
     * @param kingRealInventoryEntity 金蝶-即时库存，出入库实时更新
     * @return 金蝶-即时库存，出入库实时更新
     */
    @Override
    public AjaxResult selectKingRealInventoryEntityList ( KingRealInventoryEntity kingRealInventoryEntity ) {
        //检查系统是否存在出入库单未审核状态
        int count = iKingInventoryService.count ( new QueryWrapper<KingInventoryEntity> ().
                eq ( "state", ConstUtil.STATE_IN_PROCESS ) );
        if ( count > 0 ) {
            throw new CustomException ( "系统中存在未审核的出入库单，请先审批完成后再统计盈亏单！" );
        }
        kingRealInventoryEntity.setPage ( ( kingRealInventoryEntity.getPage () - 1 ) * kingRealInventoryEntity.getLimit () );
        List<KingRealInventoryEntity> list = kingRealInventoryMapper.selectKingRealInventoryEntityList ( kingRealInventoryEntity );
        PageParam pageParam = new PageParam ();
        pageParam.setTotal ( kingRealInventoryMapper.queryCount ( kingRealInventoryEntity ) ).setRecords ( list ).setSize ( list.size () ).setCurrent ( kingRealInventoryEntity.getPage () );
        return AjaxResult.success ( pageParam );
    }


    /**
     * 通过即时库存生成盈亏单
     *
     * @param kingRealInventoryDto
     * @return
     */
    @Override
    public AjaxResult saveInventory ( KingRealInventoryDto kingRealInventoryDto ) {
        List<KingRealInventoryEntity> kingRealInventoryEntities = kingRealInventoryDto.getKingRealInventoryEntities ();
        //提取所有盘盈数据
        List<KingRealInventoryEntity> profitEntities = kingRealInventoryEntities.stream ().filter ( profit -> Integer.parseInt ( profit.getProfitNum () ) > 0 ).collect ( Collectors.toList () );
        //提取所有盘库数据
        List<KingRealInventoryEntity> lossEntities = kingRealInventoryEntities.stream ().filter ( loss -> Integer.parseInt ( loss.getLossNum () ) > 0 ).collect ( Collectors.toList () );
        //1.处理盘盈单
        List<KingProfitLossDetailEntity> profitDetailEntities = new ArrayList<> ();
        profitEntities.forEach ( profit -> {
            KingProfitLossDetailEntity detailEntity = new KingProfitLossDetailEntity ();
            detailEntity.setMaterialCode ( profit.getMaterialCode () );
            detailEntity.setInventoryNum ( profit.getInventoryNum () );
            detailEntity.setCheckNum ( profit.getCheckNum () );
            detailEntity.setProfitLossNum ( profit.getProfitNum () );
            detailEntity.setWarehouseCode ( profit.getWarehouseCode () );
            profitDetailEntities.add ( detailEntity );
        } );
        //如果有盘盈单明细
        if ( profitDetailEntities.size () > 0 ) {
            KingProfitLossEntity profitLossEntity = new KingProfitLossEntity ();
            profitLossEntity.setBizTime ( DateUtils.getNowDate () );
            profitLossEntity.setType ( ConstUtil.INVENTORY_PROFIT_TYPE );
            profitLossEntity.setInventoryOrgCode ( CurrentUserUtil.getCompanyId () ); //当前登录组织Id，要换成Code
            KingProfitLossDto dto = new KingProfitLossDto ();
            dto.setKingProfitLossEntity ( profitLossEntity );
            dto.setKingProfitLossDetailEntities ( profitDetailEntities );
            iKingProfitLossService.draft ( dto );
        }

        //2.处理盘亏单
        List<KingProfitLossDetailEntity> lossDetailEntities = new ArrayList<> ();
        lossEntities.forEach ( loss -> {
            KingProfitLossDetailEntity detailEntity = new KingProfitLossDetailEntity ();
            detailEntity.setMaterialCode ( loss.getMaterialCode () );
            detailEntity.setInventoryNum ( loss.getInventoryNum () );
            detailEntity.setCheckNum ( loss.getCheckNum () );
            detailEntity.setProfitLossNum ( loss.getProfitNum () );
            detailEntity.setWarehouseCode ( loss.getWarehouseCode () );
            lossDetailEntities.add ( detailEntity );
        } );
        if ( lossDetailEntities.size () > 0 ) {
            KingProfitLossEntity profitLossEntity = new KingProfitLossEntity ();
            profitLossEntity.setBizTime ( DateUtils.getNowDate () );
            profitLossEntity.setType ( ConstUtil.INVENTORY_LOSS_TYPE );
            profitLossEntity.setInventoryOrgCode ( CurrentUserUtil.getCompanyId () ); //当前登录组织Id，要换成Code
            KingProfitLossDto dto = new KingProfitLossDto ();
            dto.setKingProfitLossEntity ( profitLossEntity );
            dto.setKingProfitLossDetailEntities ( profitDetailEntities );
            iKingProfitLossService.draft ( dto );
        }
        return AjaxResult.success ();
    }

    /**
     * 新增金蝶-即时库存，出入库实时更新
     *
     * @param kingRealInventoryEntity 金蝶-即时库存，出入库实时更新
     * @return 结果
     */
    @Override
    public int insertKingRealInventoryEntity ( KingRealInventoryEntity kingRealInventoryEntity ) {
        kingRealInventoryEntity.setCreateTime ( DateUtils.getNowDate () );
        return kingRealInventoryMapper.insertKingRealInventoryEntity ( kingRealInventoryEntity );
    }

    /**
     * 修改金蝶-即时库存，出入库实时更新
     *
     * @param kingRealInventoryEntity 金蝶-即时库存，出入库实时更新
     * @return 结果
     */
    @Override
    public int updateKingRealInventoryEntity ( KingRealInventoryEntity kingRealInventoryEntity ) {
        kingRealInventoryEntity.setUpdateTime ( DateUtils.getNowDate () );
        return kingRealInventoryMapper.updateKingRealInventoryEntity ( kingRealInventoryEntity );
    }

    /**
     * 批量删除金蝶-即时库存，出入库实时更新
     *
     * @param ids 需要删除的金蝶-即时库存，出入库实时更新ID
     * @return 结果
     */
    @Override
    public int deleteKingRealInventoryEntityByIds ( String[] ids ) {
        return kingRealInventoryMapper.deleteKingRealInventoryEntityByIds ( ids );
    }

    /**
     * 删除金蝶-即时库存，出入库实时更新信息
     *
     * @param id 金蝶-即时库存，出入库实时更新ID
     * @return 结果
     */
    @Override
    public int deleteKingRealInventoryEntityById ( String id ) {
        return kingRealInventoryMapper.deleteKingRealInventoryEntityById ( id );
    }

    @Override
    public KingRealInventoryEntity getRealInventoryByMaterialAndWarehouseAndPosition(KingRealInventoryQueryDto realInventoryQueryDto) {
        return kingRealInventoryMapper.getRealInventoryByMaterialAndWarehouseAndPosition(realInventoryQueryDto);
    }

}
